import { check } from 'meteor/check';
import { JoinServer } from 'meteor-publish-join';
import { Apps } from '/imports/models/Apps';
import { ChannelApps } from '/imports/models/ChannelApps';

/**
 * 获取所有app列表
 * @param {Object} query
 * @param {Number} limit
 */
Meteor.publish('get.apps', function (query, limit) {
  check(limit, Number);
  Counts.publish(this, 'get.apps.counts', Apps.find({}));
  return Apps.find({});
});

/**
 * 获取频道已安装的app列表
 * @param {Object} query
 * @param {Number} limit
 */
Meteor.publish('get.channel.apps', function (query, limit) {
  check(query.channelId, String);
  check(limit, Number);

  const selector = {
    channelId: query.channelId
  };
  
  const pipeline = [{
      $match: selector
    },
    {
      $sort: {
        createdAt: -1
      }
    },
    {
      $lookup: {
        from: 'apps',
        localField: 'appId',
        foreignField: '_id',
        as: 'apps'
      }
    },
    {
      $addFields: {
        app: {
          $arrayElemAt: ["$apps", 0]
        }
      }
    },
    {
      $project: {
        apps: 0
      }
    },
    {
      $limit: limit
    }
  ];

  JoinServer.publish({
    context: this,
    name: 'get.channel.apps.counts',
    interval: 0,
    doJoin() {
      return ChannelApps.find(selector).count();
    }
  });

  ReactiveAggregate(this, ChannelApps, pipeline, {
    clientCollection: 'clientChannelApps'
  });
});